package com.farm.wcp.online.config;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Component
public class SaveZipFile {
	@Resource
	private FilePath filePath;
	private String zipPath;
	private static final String INDEX="index.html";
	public String getZipPath() {
		return zipPath;
	}
	public void setZipPath(String zipPath) {
		this.zipPath = zipPath;
	}
	private String indexPath;
	
	public String getIndexPath() {
		return indexPath;
	}
	public void setIndexPath(String indexPath) {
		this.indexPath = indexPath;
	}
	private String docPath;
	public String getDocPath() {
		return docPath;
	}
	public void setDocPath(String docPath) {
		this.docPath = docPath;
	}
	public Boolean save(String serverPath,CommonsMultipartFile multipartFile){
		try {
			if(this.verify(multipartFile.getInputStream())){
				ZipInputStream 	Zin = new ZipInputStream(multipartFile.getInputStream());
				BufferedInputStream Bin=new BufferedInputStream(Zin);
				this.setDocPath(this.filePath.getFilePath());
				this.indexPath=this.getDocPath()+File.separator+this.indexPath;
				String path=serverPath+this.docPath; //输出路径（文件夹目录）				
				ZipEntry entry;	
				File file=null;
				while((entry=Zin.getNextEntry())!=null )
				{							
					if(!entry.isDirectory()){					
						String p=path+File.separator+entry.getName();					
						file=new File(p);
						if(!file.getParentFile().exists())
						{ 
							file.getParentFile().mkdirs();		
						}
						FileOutputStream out=new FileOutputStream(file);						
						BufferedOutputStream Bout=new BufferedOutputStream(out);
						byte[] b=new byte[1024];
						while(Bin.read(b)>0){
							Bout.write(b);
						}
						Bout.close();
						out.close();
					}					
				}
				Bin.close();
				Zin.close();
				multipartFile.transferTo(new File(path,multipartFile.getOriginalFilename()));
				this.setZipPath(this.docPath+File.separator+multipartFile.getOriginalFilename());
				return true;
			}
			else				
				return false;
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return false;
		}		
	}	
	public Boolean verify(InputStream stream) throws IOException{
		Boolean b=false;
		ZipInputStream zipInputStream=	new ZipInputStream(stream);
		int i=0;		
		ZipEntry entry;		
		while((entry=zipInputStream.getNextEntry())!=null){		
			if(i==0)			
			this.indexPath=entry.getName()+INDEX;			
			if(this.indexPath.equals(entry.getName())){
				b=true;
				break;
			}
			i++;
		}
		zipInputStream.close();
		stream.close();
		return b;
	}

}
